package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WeMediaThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 分页条件查询自媒体文章
     * @param dto
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1、参数校验
        dto.checkParam();
        if(dto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        
        //2、构建分页条件构造器
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.1状态精准查询
        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //2.2频道id精准查询
        if(dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //2.3关键字模糊查询 like
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //2.4开始结束时间范围查询 between
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //3、查询数据库
        page(page,lambdaQueryWrapper);

        //4、封装结果返回
        PageResponseResult result = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        result.setData(page.getRecords());

        return result;
    }



    /**
     * 文章发布
     * @param dto
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //1、参数校验
        if(dto == null || dto.getContent() == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //2、数据处理
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);//封装文章对象，copy只能复制属性名一致的
        //2.1处理图像
        if(dto.getImages() != null && dto.getImages().size() > 0){
            String image = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(image);
        }
        //2.2如果封面类型为自动 -1，置为null后期处理
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO))
            wmNews.setType(null);

        //3、根据是否存在文章id判断 保存/修改文章
        saveOrUpdateNews(wmNews);

        //4、判断是否为草稿，若为草稿则结束
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode()))
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        //5、不是草稿，则关联文章内容图片与素材的关系
        List<String> materials = ectracUrlInfo(dto.getContent());//获取文章内容中的图片信息
        saveRelativeInfoForContent(materials,wmNews.getId());//根据materialId、newsId保存

        //6、不是草稿，则关联文章封面图片与素材的关系
        saveRelativeInfoForCover(dto,wmNews,materials);//封面图片可能在文章内容中（materials)，也可能在素材中

//        //文章发布之后对其进行审核
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        //文章发布完成后，异步添加任务到数据库以完成延迟业务
        wmNewsTaskService.addNewsToTask(wmNews.getId(),dto.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //文章上下架
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.参数校验
        if(dto.getId() == null || dto.getEnable() == null || (dto.getEnable() != 0 && dto.getEnable() != 1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //2.根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");

        //3.存在则判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架操作");

        //4.修改文章enable(1:上架 0:下架)
        update(Wrappers.<WmNews>lambdaUpdate()
                .set(WmNews::getEnable,dto.getEnable())
                .eq(WmNews::getId,wmNews.getId()));

        /**
         * 文章上下架之后通过kafka发送消息到article
         * */
        if(wmNews.getArticleId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send(WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    /**
     * 查询文章列表
     *
     * @param dto
     */
    @Override
    public ResponseResult listVo(NewsAuthDto dto) {
        //1.参数校验
        if(dto == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //2.构建分页构造器
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(dto.getTitle()))
            lqw.like(WmNews::getTitle,dto.getTitle());
        if(dto.getStatus() != null)
            lqw.eq(WmNews::getStatus,dto.getStatus());

        //3.查询数据
        page(page,lqw);

        //4.封装结果返回
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
//todo 缺少作者名称
        return result;
    }

    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     *
     * @param id
     */
    @Override
    public ResponseResult oneVo(Integer id) {
        //1.参数校验
        if(id == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //2.业务处理
        //2.1获取文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //获取用户信息以返回作者名称
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);

        //3.封装数据返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());

        return ResponseResult.okResult(wmNewsVo);
    }

    /**
     * 自媒体文章人工审核
     */
    @Override
    public ResponseResult passOrFail(NewsAuthDto dto, Short status) {
        //1.参数校验
        if(dto == null || dto.getId() == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //2.业务处理
        //2.1获取文章信息
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //2.2修改文章的状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())) wmNews.setReason(dto.getMsg());

        updateById(wmNews);

        //2.3审核通过：创建app端的文章信息，并更新自媒体文章的状态
        if(status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)){
            //创建app端文章数据
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(wmNews,articleDto);
            ResponseResult responseResult = iArticleClient.saveOrUpdate(articleDto);
            if(responseResult.getCode().equals(200)){
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                updateById(wmNews);
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }







    /**
     * 关联文章封面图片与素材的关系,如果当前布局是自动，需要匹配封面图片
     * */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();//前端传来的封面图片数据
        //布局为自动
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //多图
            if(materials.size() >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //将内容图片中的前三张截取作为封面图片
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if(materials.size() >= 1 && materials.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if(images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);
        }
        //非自动
        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 根据materialId、newsId保存
     * */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);//保存到数据库
    }

    /**
     * 保存图片与素材的关系 --参数校验获取素材id
     * */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //参数校验
        if(materials !=null && newsId != null){
            //1、通过图片的url查询素材以获取materialId
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //2、判断素材是否有效
            if(idList.size() != materials.size())
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            //批量保存
            wmNewsMaterialMapper.saveRelations(idList,newsId,type);
        }
    }

    /**
     * 获取文章内容中的图片信息
     * */
    private List<String> ectracUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content,Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }
        return materials;
    }

    /**
     * 保存或修改文章
     * */
    private void saveOrUpdateNews(WmNews wmNews) {
        wmNews.setUserId(WeMediaThreadLocalUtil.get());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架

        if(wmNews.getId() == null){
            //保存
            save(wmNews);
        }else {
            //修改
            //.1删除文章和素材的关联关系
            LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(wrapper);
            //.2修改文章
            updateById(wmNews);
        }
    }

}
